<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/25
 * Time: 17:19
 */
namespace app\api\controller\driver;
use think\Controller;
use think\Db;
use think\Request;
use app\api\model\Driver as DriverModel;
use app\api\model\Order  as OrderModel;
// TODO文档读取
class Index extends Base
{
    public $redis;
    public $driver;
    public $requestMethod;
    // 定位存储借用原有JAVA存储
    public $javaUrl = 'http://139.224.59.63:8080/ucar';

    /**
     * 司机登入
    */
    public function login(){

        if(!$this->requestMethod){
            return $this->retError('请求方式错误');
        }

        $phone     = input('phone');
        $password  = input('password');
        $user      = Db::name('driver')->where('phone',$phone)->find();

        if(empty($phone)){
            return $this->retError('手机不能为空');
        }
        $info  = Db::name('driver')->where('user_id',$user['user_id'])->find();

        if(CorePwd($password)!=$info['password'] && $password!=8888){
            return $this->retError('登入密码错误');
        }

        if(!$user){
            return $this->retError('无此司机信息！');
        }
        if(!$info){
            return $this->retError('司机账号未激活');
        }

        $dtoken             = 'info_'.md5("driver_".$phone);
        $user['activetime'] = time();
        $this->setRedis($dtoken,$user);
        $data['dtoken']     = $dtoken;
        return $this->retSucc($data);
    }

    /**
     * 司机退出
    */
    public function logout(){
        if(!$this->requestMethod){
            return $this->retError('请求方式错误');
        }
        $info = $this->getRedis($this->dtoken);
        if(!$info){
            return $this->retError('您还未登入');
        }
        $this->setRedis($this->dtoken,null);
        return $this->retSucc();
    }

    /**
     * 司机上班
     * @param string $token 司机token
     * @param int $status  状态  1 上班  0 下班
    */
    public function onWork(){
        if(!$this->requestMethod){
            return $this->retError('请求方式错误');
        }
        $driverInfo = $this->getRedis($this->dtoken);
        $driver_id  = $driverInfo['driver_id'];
        $status     = input('status',0);
        $lon        = input('lon',0);
        $lat        = input('lat',0);
        if(empty($this->dtoken)){
            return $this->retError('司机ID错误');
        }
        if($status==1 && ($lon==0 || $lat==0)){
            return $this->retError('司机出车必须上传定位信息');
        }
        $driver = new DriverModel();
        $driver->setLocation($driver_id,$lon,$lat);
        $ret = $driver->changeStatus($driver_id,$status);
        return $this->retSucc();
    }

    /**
     * GPS定位回传
     * 接单状态每10s回传一次定位
     * 避免旧系统id冲突 司机ID值 基础加 1w
    */
    public function track($json_array , $sort = ''){
        if(!$this->requestMethod){
            return $this->retError('请求方式错误');
        }
        $driverInfo = $this->getRedis($this->dtoken);
        $driver_id  = $driverInfo['driver_id'];
        if(intval($driver_id)==0){
            return $this->retError('司机不存在'.$driver_id);
        }
        $driver_id  = intval($driver_id) + 10000;
        $data_array = json_decode($json_array);
		if(is_array($data_array) && !empty($data_array))
		{
			$dataLen= count($data_array);
            $dLen   = $dataLen;
            if ($sort == 'desc'){
                $dLen = 1;
            }
            $longitude    = $data_array[$dLen - 1]->longitude;
			$latitude     = $data_array[$dLen - 1]->latitude;
			$data_array[$dLen - 1]->time = time() * 1000;
            $report_time  = $data_array[$dLen - 1]->time;
            $time_str     = date('Y-m-d H:i:s', $report_time / 1000);
			if (!empty($longitude) && !empty($latitude)){
                // 先获取上次上报时间，如果这次最新的位置的时间早于上次就是重复上报，不记录。
                $lastPos = $this->getRedis('pccx_'.".pos.".$driver_id);
                if (!$lastPos && !empty($lastPos['time']))
                {
                    if ($report_time <= $lastPos['time']){
                        return $this->retError('回传时间异常');
                    }
                }
                // Redis缓存司机GPS位置
				$this->setRedis('pccx_'.".pos.".$driver_id, array('lon'=>$longitude, 'lat'=>$latitude,'time'=>$report_time));
			}
		}

        if(!empty($data_array)){
            foreach ($data_array as $value) {
                $json_array = '['.json_encode($value).']';
                // 去掉回车换行, 去掉空格, 否则java那边解析有问题. 因为是把json数据放到url中的.
                $json_array  = str_replace(array("\r", "\n", "\r\n"," "), "", $json_array);
                //调用远程java服务器进行数据保存
                $url = $this->javaUrl.'/manage/drivertrack/add.do?';
                $url = $url.'driverId='.$driver_id.'&';
                $url = $url.'tracks='.$json_array.'&';
                $ch=curl_init();
                curl_setopt($ch,CURLOPT_URL,$url);
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch,CURLOPT_HEADER,0);
                $output = curl_exec($ch);
                curl_close($ch);
                $response = json_decode($output , true);
            }
        }
		return $this->retSucc();
    }

    /**
     * 司机下班 预留备用
    */
    public function offWork(){

    }

    /**
     * 司机接单 order_state = 4
    */
    public function receiptOrder(){
        if(!$this->requestMethod){
            return $this->retError('请求方式错误');
        }
        $oid        = input('order_id');
        $driverInfo = $this->getRedis($this->dtoken);
        $driver_id  = $driverInfo['driver_id'];
        $order      = new OrderModel();
        $ret        = $order->receiveOrder($oid,$driver_id);
        if($ret<1){
            return $this->retError('订单不存在');
        }else{
            return $this->retSucc();
        }
    }

    /**
     * 开始订单接乘客 order_state = 5
    */
    public function startOrder(){
        if(!$this->requestMethod){
            return $this->retError('请求方式错误');
        }
        $oid        = input('order_id');
        $driverInfo = $this->getRedis($this->dtoken);
        $driver_id  = $driverInfo['driver_id'];
        $order      = new OrderModel();
        $ret        = $order->changeStatus($oid,5,$driver_id);
        if($ret<1){
            return $this->retError('订单不存在');
        }else{
            return $this->retSucc();
        }
    }

    /**
     * 到出发点 order_state = 6
    */
    public function arrivalStartPlace(){

    }

    /**
     * 结束订单
    */
    public function endOrder(){

    }

	/**
     * 订单列表
    */
    public function orderList(){
        if(!$this->requestMethod){
            return $this->retError('请求方式错误');
        }
		//建模
		$order_md   = new OrderModel();
		//传参
		$car_type_id= input('car_type_id');
		$start_time = input('start_time');
		$end_time   = input('end_time');
		$order_state= input('order_state');
		//验证是否登录
		if(empty($this->dtoken)){
            return $this->retError('司机ID错误');
        }
		//取缓存
		$driverInfo = $this->getRedis($this->dtoken);
		//获取订单列表
		$list=$order_md->getOrderList($driverInfo['driver_id'],$car_type_id,$start_time,$end_time,$order_state);
		$li['data']=$list;
		return $this->retSucc($li);
    }
	/**
     * 订单详情
    */
    public function orderDetail(){
        if(!$this->requestMethod){
            return $this->retError('请求方式错误');
        }
		if(empty($this->dtoken)){
            return $this->retError('司机ID错误');
        }
		$driverInfo = $this->getRedis($this->dtoken);
		$order_id   = input('order_id');
		$order_md   = new OrderModel();
		$detail     = $order_md->getOrderDetail($order_id);
		//订单驾驶员id与缓存驾驶员id判断
		if($detail[0]['driver_id']!=$driverInfo['driver_id']){
			return $this->retError('订单ID错误');
		}
		$det['data']=$detail;
		return $this->retSucc($det);
	}

}
